
package net.swa.system.util.ws.interceptor;

import net.swa.system.util.ws.vo.IpAuthConfig;

import org.apache.log4j.Logger;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.springframework.beans.factory.annotation.Required;

/**
 * CXF服务IP鉴权拦截器
 * [一句话功能简述]<p>
 * [功能详细描述]<p>
 * @author FangZheng
 * @version 1.0, 2012-2-5
 * @see net.swa.system.util.ws.vo.core.domain.vo.IpAuthConfig
 * @since V1.0
 */
public class CxfIpAuthInterceptor extends AbstractPhaseInterceptor<Message>
{
    /**
    * Logger for this class
    */
    private static final Logger log = Logger.getLogger(CxfIpAuthInterceptor.class);

    private IpAuthConfig ipAuthConfig;

    @Required
    @Resource
    public void setIpAuthConfig(IpAuthConfig ipAuthConfig)
    {
        this.ipAuthConfig = ipAuthConfig;
    }

    public CxfIpAuthInterceptor()
    {
        super(Phase.RECEIVE);
    }

    @Override
    public void handleMessage(Message message) throws Fault
    {
        HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
        //允许访问的IP地址     
        List<String> allowedList = ipAuthConfig.getAllowedList();
        //拒绝访问的IP地址 
        List<String> deniedList = ipAuthConfig.getDeniedList();
        //取客户端IP地址  
        String ipAddress = request.getRemoteAddr();
        if (log.isDebugEnabled())
        {
            log.debug("访问CXF WebService的IP地址为：" + ipAddress);
        }
        //先处理拒绝访问的地址     
        if ((null != deniedList) && (0 < deniedList.size()))
        {
            for (String deniedIpAddress : deniedList)
            {
                if (ipAddress.equals(deniedIpAddress))
                {
                    throw new Fault(new IllegalAccessException("IP地址[" + ipAddress + "]在拒绝访问地址列表中"));
                }
            }
        }
        //如果允许访问的集合非空，继续处理，否则认为全部IP地址均合法     
        if ((null != allowedList) && (allowedList.size() > 0))
        {
            boolean contains = false;
            for (String allowedIpAddress : allowedList)
            {
                if (ipAddress.equals(allowedIpAddress))
                {
                    contains = true;
                    break;
                }
            }
            if (false == contains)
            {
                throw new Fault(new IllegalAccessException("IP地址[" + ipAddress + "]不在允许访问的地址列表中"));
            }
        }
    }
}
